package org.example.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.embedded.EmbeddedChannel;

public class DynamicHandlerTest {
    public static void main(String[] args) {
        ChannelHandler channelHandler = new ChannelInitializer<EmbeddedChannel>() {
            @Override
            protected void initChannel(EmbeddedChannel ch) throws Exception {
                ch.pipeline().addLast(new SimpleHandlerA());
                ch.pipeline().addLast(new SimpleHandlerB());
                ch.pipeline().addLast(new SimpleHandlerC());
            }
        };

        EmbeddedChannel channel = new EmbeddedChannel(channelHandler);

        ByteBuf buffer = Unpooled.buffer();
        buffer.writeInt(10);
        // 模拟入站
        channel.writeInbound(buffer);

        // 模拟入站
        buffer.writeInt(20);
        channel.writeInbound(buffer);

        // 模拟出站
        buffer.writeInt(30);
        channel.writeOutbound(buffer);
    }

    static class SimpleHandlerA extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("A处理器被调用");
            // 动态移除当前处理器
            ctx.pipeline().remove(this);
            super.channelRead(ctx, msg);
        }
    }

    static class SimpleHandlerB extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("B处理器被调用");
            super.channelRead(ctx, msg);
        }
    }

    static class SimpleHandlerC extends ChannelOutboundHandlerAdapter {
        @Override
        public void read(ChannelHandlerContext ctx) throws Exception {
            System.out.println("C处理器被调用read");
            super.read(ctx);
        }

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            System.out.println("C处理器被调用write");
            super.write(ctx, msg, promise);
        }
    }
}
